package r929.servletJsonpFilter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;

import org.apache.log4j.Logger;

public class JsonpServletOutputStream extends ServletOutputStream {
	
	private static final Logger logger = Logger.getLogger(JsonpServletOutputStream.class);
	
	private ServletOutputStream servletOutput	=	null;
	private ByteArrayOutputStream byteArrayOutput	=	null;
	
	public JsonpServletOutputStream(ServletOutputStream servletOutput){
		this.servletOutput	=	servletOutput;
		byteArrayOutput	=	new ByteArrayOutputStream();
	}

	@Override
	public void write(int b) throws IOException {
		byteArrayOutput.write(b);
	}

	@Override
	public void flush() throws IOException {
		byteArrayOutput.flush();
		super.close();
	}

	@Override
	public void close() throws IOException {
		byteArrayOutput.close();
		super.close();
	}
	
	public ByteArrayOutputStream getByteArrayOutput(){
		return byteArrayOutput;
	}
	
	public ServletOutputStream getServletOutput(){
		return servletOutput;
	}
	
	public void flushBufferToServletOutput() throws IOException{
		byteArrayOutput.flush();
		servletOutput.write(byteArrayOutput.toByteArray());
		servletOutput.flush();
	}
	
	public String getJsonResult(String charsetName) throws UnsupportedEncodingException{
		return byteArrayOutput.toString(charsetName);
	}
}
